<template>
  <!-- 检查区域-树下拉框查询 -->
  <a-tree-select v-bind="$attrs" v-on="$listeners" v-model="currentValue" :tree-data="treeData" allowClear
    :showSearch="isShowSearch" :tree-default-expanded-keys="treeDefaultExpandedKeys" :maxTagCount="maxTagCount"
    :filterTreeNode="fillter" :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
    :show-checked-strategy="SHOW_PARENT" :placeholder="placeholder">
    <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
  </a-tree-select>
</template>
<script>
import { setSubItem } from '@/api/quality/currency' // api
import { TreeSelect } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT

export default {
  name: 'SelectTreeDistrict',
  data() {
    return {
      fetching: false,
      isCanClear: !this.isEdit,
      treeData: [],
      dataList: [],
      SHOW_PARENT,
      treeDefaultExpandedKeys: []
    }
  },
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object]
    },
    // placeholder
    placeholder: {
      type: String,
      default: function () {
        return '请选择'
      }
    },
    // 项目id
    projectId: {
      type: [String, Number],
      default: function () {
        return ''
      }
    },
    // 多选状态下,最大显示选项数
    maxTagCount: {
      type: Number,
      default: function () {
        return 2
      }
    },
    // 表单
    form: Object,
    // 是否初始化
    init: {
      type: Boolean,
      default: () => false
    },
    keyValue: {
      type: String,
      default: () => 'projectId'
    },
    //如果是编辑，第一次不要重置绑定的值。。。。
    isEdit: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否不显示禁用节点
    enabled: {
      type: Boolean,
      default() {
        return true
      }
    },
    // 是否为继承
    isInherit: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 需要禁用节点的列表
    enabledList: {
      type: Array,
      default() {
        return []
      }
    },
    // 是否启用禁用功能
    isDisabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否禁用除末级以外节点
    fatherDisabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否显示搜索框
    isShowSearch: {
      type: Boolean,
      default() {
        return true
      }
    },
    // 是否只显示第一级
    isFirstNode: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否删除请求参数ProjectId
    deleteProjectId:{
      type: Boolean,
      default() {
        return false
      }
    },
    //是否禁用inherit为false的数据
    disableInherit:{
      type: Boolean,
      default() {
        return false
      } 
    },
      // 是否禁用除末级以外节点
    finalNode:{
     type: Boolean,
      default() {
        return false
      }
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.$attrs.treeCheckStrictly && (this.$attrs.treeCheckable || this.$attrs.multiple) ? this.value?.map((item) => ({ value: item, label: this.dataList?.find((i) => i.name === item)?.name })) : this.value
      },
      set: function (value) {
        this.$emit('input', this.$attrs.treeCheckStrictly && (this.$attrs.treeCheckable || this.$attrs.multiple) ? value?.map((item) => item.value) : value)
      }
    },
    attr() {
      return this.form?.[this.keyValue]
    }
  },
  watch: {
    // 监听禁用列表重新渲染列表
    enabledList: {
      deep: true,
      handler(e) {
        this.dataList?.forEach((item) => {
          e.length && (item.disabled = (this.isDisabled && !item.inherit) || this.enabledList?.includes(item.id))
        })
      }
    },
    // 监听项目id和工程类别id
    projectId(e) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = ''
      }
      // 清空表单
      if (this.isEdit && this.isCanClear) {
        this.currentValue = ''
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      } else {
        this.isCanClear = true
      }
      // 重置列表
      this.treeData = []
      if (e) {
        this.getList()
      }
    },
    attr(val) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = ''
      }
      // 清空表单
      if (this.isEdit && this.isCanClear) {
        this.currentValue = ''
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      } else {
        this.isCanClear = true
      }
      // 重置列表
      this.treeData = []
      val && this.getList()
    }
  },
  methods: {
    /**
     * 筛选节点
     */
    fillter(searchVal, treeNode) {
      return treeNode?.data?.props?.label?.includes(searchVal)
    },
    /**
     * 获取单极全部节点
     */
    getData(data) {
      data.forEach((item) => {
        this.dataList.push(item)
        // inherit:是否可继承;enabledList:禁用节点列表；
        if (this.isDisabled) {
          item.disabled = !item.inherit || this.enabledList?.includes(item.id)
        }
        item.label = item.name
        if (item.children?.length > 0) {
          if (this.fatherDisabled) {
            item.disabled = true
          }
          this.getData(item.children)
        }
      })
    },
    /**
     * 获取树
     */
    getList() {
      // 获取下拉框列表
      let args = {
        enabled: this.enabled,
        isInherit: this.isInherit
      }
      // 项目id存在则添加
      this.form?.projectId && this.form?.projectId !== "null" && (args.id = this.form?.projectId)
       // 项目id存在则添加
      this.projectId && (args.id = this.projectId)
      this.form?.[this.keyValue] && (args[this.keyValue === 'projectId' ? this.keyValue : 'id'] = this.form[this.keyValue])
      if (!args.id) {
        return false
      }
      this.fetching = true
      this.deleteProjectId && delete args.projectId
      setSubItem
        .getList(args)
        .then((res) => {
          this.fetching = false
          if (res.code == 200) {
            this.treeData = res.data[0].children
            this.disableInherit && this.isDisabledFn(this.treeData )
            this.finalNode && this.finalNodeFn(this.treeData)
            this.treeDefaultExpandedKeys = !this.isFirstNode ? [this.treeData[0].children[0].id] : []
          }
        })
        .catch(() => {
          this.fetching = false
        })
    },
    isDisabledFn(data){
      return data && data.map((item)=>{
           if(Array.isArray(item.children) && item.children.length > 0){
            item.disabled = !item.inherit;  
            return  this.isDisabledFn(item.children)
           }else{
             item.disabled = !item.inherit;  
           }
        })
    },
    finalNodeFn(data){
       return data && data.map((item)=>{
           if(Array.isArray(item.children) && item.children.length > 0){
            item.disabled = true;  
            return  this.finalNodeFn(item.children)
           }else{
             item.disabled = false;  
           }
        })
    }
  },
  mounted() {
     if (this.init || this.projectId || this.typeId) {
      this.getList()
    }
  }
}
</script>
